package com.itxialu.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itxialu.reggie.common.R;
import com.itxialu.reggie.entity.User;
import com.itxialu.reggie.service.UserService;
import com.itxialu.reggie.utils.SMSUtils;
import com.itxialu.reggie.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import javax.websocket.Session;
import java.util.Map;

/**
 * 用户信息
 *
 * @author shkstart
 * @create 2022-11-05 16:28
 */
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    //发送手机短信验证码
    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpSession session) {
        System.out.println("发送手机短信验证码");
        //1.获取手机号
        String phone = user.getPhone();
        if (StringUtils.isNotEmpty(phone)) {
            //2.调用工具类，随机生成4位手机验证码
            String code = ValidateCodeUtils.generateValidateCode(4).toString();
            //3.调用短信API短信发送服务
            SMSUtils.sendMessage("阿里云短信测试", "SMS_154950909", phone, code);
            //4.保存短信验证码--保存在Session，校验前端输入的对不对
            session.setAttribute(phone, code);
            return R.success("手机验证码短信发送成功");
        }
        return R.error("短信发送失败");
    }

    //登录的方法
    @PostMapping("/login")
    public R<User> login(@RequestBody Map map, HttpSession session) {
        log.info("进入登录的方法{}", map);
        //1.获取手机号
        String phone = map.get("phone").toString();
        //2.获取验证码
        String code = map.get("code").toString();
        //3.从Session中获取验证码
        //Object codeInSession = session.getAttribute(phone);
        Object codeInSession = code;
        //4.验证码对比：本地与前端
        if (codeInSession != null && codeInSession.equals(code)) {
            System.out.println("验证码比对成功！");
            //5.判断手机号是否为新用户
            LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(User::getPhone, phone);
            User user = userService.getOne(wrapper);//看看数据库有没有此手机号
            if (user == null) {
                System.out.println("数据库没有此手机号，创建新用户");
                user = new User();
                user.setPhone(phone);
                userService.save(user);
            }
            session.setAttribute("user", user.getId());
            return R.success(user);
        }
        return R.error("登录失败");
    }

}
